package openjdk.security;

import java.security.*;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by boot on 8/29/15.
 */
public class DSA {

    private String src = "I like raydoz";

    public static void main(String[] args) {

        new DSA().jdkDSA();
    }

    public void jdkDSA() {

        try {
            // init key pair

            KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA");
            generator.initialize(512);
            KeyPair keyPair = generator.generateKeyPair();
            DSAPublicKey dasPublicKey = (DSAPublicKey) keyPair.getPublic();
            DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) keyPair.getPrivate();

            // sign

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(dsaPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("DSA");
            PrivateKey pk = keyFactory.generatePrivate(spec);
            Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initSign(pk);
            signature.update(src.getBytes());

            byte[] result = signature.sign();


            // verify

            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(dasPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("DSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            Signature sign = Signature.getInstance("SHA1withDSA");
            sign.initVerify(publicKey);
            sign.update(src.getBytes());
            boolean b = sign.verify(result);
            System.out.println("jdk DSA verify:" + b);


        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        }

    }
}
